﻿using Common.Communication;
using Common.Device.Enums;
using Common.Device.Interfaces;
using Common.Device.ViewModels;
using Common.Tool.DataTools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Common.Device.Models
{
    public class TongXin : Device
    {
        /// <summary>
        /// 测试模式
        /// </summary>
        public TongXinEnum.TestMode mode { get; set; }
        public string 类型 { get; set; }
        public string 发送内容 { get; set; }
        public bool 换行符 { get; set; }
        public bool 正则校验 { get; set; }
        public int 等待时间 { get; set; }
        public string 接收内容 { get; set; }
        /// <summary>
        /// 获取测试指令
        /// </summary>
        /// <param name="deviceName">仪器名</param>
        /// <returns></returns>
        public override Order GetOrder(string deviceName)
        {
            //测试指令
            Order order = new Order();
            order.temp = mode.ToString();
            order.name = deviceName;
            switch (mode)
            {
                case TongXinEnum.TestMode.仅发送:
                    order.deviceModel = JsonConvert.SerializeObject(new { 类型, 发送内容, 换行符 }); break;
                case TongXinEnum.TestMode.仅接收:
                    order.range = 接收内容;
                    order.deviceModel = JsonConvert.SerializeObject(new { 类型, 等待时间, 接收内容,正则校验 }); break;
                case TongXinEnum.TestMode.发送并接收:
                    order.range = 接收内容;
                    order.deviceModel = JsonConvert.SerializeObject(new { 类型, 发送内容, 换行符, 等待时间, 接收内容,正则校验 }); break;
                default:
                    break;
            }
            return order;
        }
        /// <summary>
        /// 测试并返回测试结果
        /// </summary>
        /// <param name="dev">仪器实体</param>
        /// <param name="testOrder">测试项</param>
        /// <returns></returns>
        public override DeviceResult GetResult(object dev, TestOrder testOrder)
        {
            ITongXin device = dev as ITongXin;
            var result = new DeviceResult();
            //换行字符
            if (换行符 && 类型 == TongXinEnum.DataType.ASCII.ToString())
            {
                发送内容 += "\r\n";
            }
            if (换行符 && 类型 == TongXinEnum.DataType.HEX.ToString())
            {
                发送内容 += " 0D 0A";
            }
            switch (mode)
            {
                case TongXinEnum.TestMode.仅发送:
                    var r1 = device.Send((TongXinEnum.DataType)Enum.Parse(typeof(TongXinEnum.DataType), 类型), 发送内容);
                    result.success = r1.IsSucceed;
                    result.result = r1.IsSucceed ? "OK" : r1.Err;
                    break;
                case TongXinEnum.TestMode.仅接收:
                case TongXinEnum.TestMode.发送并接收:
                    var r2 = new Result<byte[]>();
                    if (mode == TongXinEnum.TestMode.仅接收)
                    {
                        r2 = device.Receive((TongXinEnum.DataType)Enum.Parse(typeof(TongXinEnum.DataType), 类型), 等待时间);
                    }
                    if (mode == TongXinEnum.TestMode.发送并接收)
                    {
                        r2 = device.SendAndReceive((TongXinEnum.DataType)Enum.Parse(typeof(TongXinEnum.DataType), 类型),发送内容, 等待时间);
                    }
                    if (r2.IsSucceed == false)
                    {
                        result.success = false;
                        result.result = r2.Err;
                        break;
                    }
                    if (类型 == TongXinEnum.DataType.ASCII.ToString())
                    {
                        //返回值判断
                        var rec = Encoding.ASCII.GetString(r2.Value);
                        if (正则校验 && !Regex.IsMatch(rec, 接收内容))
                        {
                            result.success = false;
                            result.result = rec;
                            break;
                        }
                        if (!正则校验 && !rec.Contains(接收内容))
                        {
                            result.success = false;
                            result.result = rec;
                            break;
                        }
                    }
                    if (类型 == TongXinEnum.DataType.HEX.ToString())
                    {
                        //返回值判断
                        var wants = 接收内容.Split(' ');
                        var receives = DataConvert.ByteArrayToString(r2.Value).Split(' ');
                        //长度判断
                        if (wants.Length > receives.Length)
                        {
                            result.success = false;
                            result.result = "长度不一致";
                            break;
                        }
                        //获取第一个匹配上的非XX字节索引
                        int startIndex = -1;
                        string want1 = wants[0].ToUpper();
                        string want2 = wants[1].ToUpper();
                        for (int i = 0; i < receives.Length; i++)
                        {
                            if (want1 != "XX" && receives[i] == want1)
                            {
                                if (want2 == "XX")
                                {
                                    startIndex = i;
                                    break;
                                }
                                if (want2 != "XX" && i + 1 <= receives.Length && receives[i + 1] == want2)
                                {
                                    startIndex = i;
                                    break;
                                }
                            }
                        }

                        if (startIndex == -1 || receives.Length - startIndex < wants.Length)
                        {                       
                            //匹配失败
                            result.success = false;
                            result.result = DataConvert.ByteArrayToString(r2.Value);
                            break;
                        }
                        else
                        {
                            //依次对比非XX字节
                            for (int i = 0; i < wants.Length; i++)
                            {
                                string want = wants[i].ToUpper();
                                if (want != "XX")
                                {
                                    if (receives[i + startIndex] != want)
                                    {
                                        result.success = false;
                                        result.result = DataConvert.ByteArrayToString(r2.Value);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    result.success = true;
                    result.result = "OK";
                    break;
                default:
                    break;
            }
            return result;
        }
    }
}
